
package org.eteamcs.service.impl;

import java.util.List;

import org.acegisecurity.Authentication;
import org.acegisecurity.acl.basic.AclObjectIdentity;
import org.acegisecurity.acl.basic.BasicAclExtendedDao;
import org.acegisecurity.acl.basic.NamedEntityObjectIdentity;
import org.acegisecurity.acl.basic.SimpleAclEntry;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eteamcs.dao.ICompanieDAO;
import org.eteamcs.model.Companie;
import org.eteamcs.model.CompanySearch;
import org.eteamcs.service.ICompanieManager;
import org.springframework.validation.Validator;


/**
 * Manager Implementation to table companies
 * @author Paulo Neves
 * Generated by Javalee v. 1.1
 * $Id$
 */
public class CompanieManager implements ICompanieManager {
    private Log log = LogFactory.getLog(CompanieManager.class);
    private ICompanieDAO dao;
    private BasicAclExtendedDao basicAclExtendedDao;
    private Validator validator;

    public void setBasicAclExtendedDao(BasicAclExtendedDao basicAclExtendedDao) {
      this.basicAclExtendedDao = basicAclExtendedDao;
	  }
	
	  public BasicAclExtendedDao getBasicAclExtendedDao() {
	      return basicAclExtendedDao;
	  }
    
    public void setCompanieDAO(ICompanieDAO dao) {
        this.dao = dao;
    }

    public void setValidator(Validator validator) {
    	this.validator = validator;
    }

    public List getCompanies() {
    	CompanySearch cs = new CompanySearch();
      return dao.getCompanies(cs);
  }    
    
    public List getCompanies(CompanySearch cs) {
        return dao.getCompanies(cs);
    }
    
    public List getCompaniesByInitial(String initial) {
    	return dao.getCompaniesByInitial(initial);
    }    

    public Companie getCompanie(java.lang.Long companyId) {
        Companie companie = dao.getCompanie(companyId);

        if (companie == null) {
            log.warn("(companyId) '" + (companyId) + "' not found in database.");
        }

        return companie;
    }

    
    public Companie getCompanyByName(String name) {
        Companie companie = dao.getCompanieByName(name.toLowerCase());

        if (companie == null) {
            log.warn("(name) '" + (name) + "' not found in database.");
        }

        return companie;
    }
    
    public Companie saveCompanie(Companie companie) {
        /*BindException errors = new BindException(companie, "companie");
        validator.validate(companie, errors);
        if (errors.hasErrors()) {
        	throw new RuntimeException("validation failed!", errors);
        }*/
    	  boolean isNew = companie.getCompanyId()==null;
    	  
    	  	 
        dao.saveCompanie(companie);

        if(isNew) {        
	        //      Grant the current principal access to the contact 
	        addPermission(companie, getUsername(),
	            new Integer(SimpleAclEntry.READ_WRITE_CREATE_DELETE));
	        addPermission(companie, "ROLE_SUPERVISOR",
	            new Integer(SimpleAclEntry.READ_WRITE_CREATE_DELETE));        
	        addPermission(companie, "ROLE_USER",
	            new Integer(SimpleAclEntry.READ));       
	
	        if (log.isDebugEnabled()) {
	            log.debug("Created companie " + companie
	                + " and granted admin permission to recipient " + getUsername());
	        }        
        }

        return companie;
    }

    public void removeCompanie(java.lang.Long companyId) {
    	  Companie companie = dao.getCompanie(companyId);
        dao.removeCompanie(companyId);

        //  Delete the ACL information as well
        basicAclExtendedDao.delete(makeObjectIdentity(companie));

        if (log.isDebugEnabled()) {
            log.debug("Deleted companie " + companie
                + " including ACL permissions");
        }        
        
    }
    
    public void addPermission(Companie company, String recipient,
         Integer permission) {
         SimpleAclEntry simpleAclEntry = new SimpleAclEntry();
         simpleAclEntry.setAclObjectIdentity(makeObjectIdentity(company));
         simpleAclEntry.setMask(permission.intValue());
         simpleAclEntry.setRecipient(recipient);
         basicAclExtendedDao.create(simpleAclEntry);

         if (log.isDebugEnabled()) {
             log.debug("Added permission " + permission + " for recipient "
                 + recipient + " contact " + company);
         }
     }

	  protected String getUsername() {
      Authentication auth = SecurityContextHolder.getContext()
                                                 .getAuthentication();

      if (auth.getPrincipal() instanceof UserDetails) {
          return ((UserDetails) auth.getPrincipal()).getUsername();
      } else {
          return auth.getPrincipal().toString();
      }
  }

  private AclObjectIdentity makeObjectIdentity(Companie company) {
      return new NamedEntityObjectIdentity(company.getClass().getName(),
      		company.getId().toString());
  }    
    
	
}
